<template>
  <div id="app">
    <h1>{{ title }}</h1>
    <ul class="todos">
      <li>
        <input
          v-model="newTodo"
          placeholder="快写下您要我记住的事吧"
          autofocus="true"
          @keyup.13="addItem"
        >
      </li>
      <li
        v-for="(todo,index) in todos"
        :key="index"
        :class="{'checked':todo.done}"
      >
        <input
          v-model="todo.done"
          type="checkbox"
          @change="saveToStore"
        ><label>{{ index+1 }}.{{ todo.value }}</label>
        <time>{{ todo.created | date }}</time>
        <button @click.prevent="delItem(todo)" />
      </li>
    </ul>
  </div>
</template>

<script>
import './assets/site.scss'
import './assets/todos.scss'
import moment from 'moment'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')

export default {
  name: 'App',
  filters: {
    date (val) {
      return moment(val).calendar()
    }
  },
  data () {
    return {
      newTodo: '',
      title: 'vue-todos',
      todos: []
    }
  },
  computed: {
    is_initialized () {
      return localStorage.getItem('VUE-TODOS') != null
    }
  },
  created () {
    if (this.is_initialized) {
      this.todos = JSON.parse(localStorage.getItem('VUE-TODOS'))
    }
  },
  methods: {
    addItem () {
      this.todos.push({
        value: this.newTodo,
        created: Date.now(),
        done: false
      })
      this.saveToStore()
      this.newTodo = ''
    },
    delItem (todo) {
      this.todos = this.todos.filter((x) => x !== todo)
      this.saveToStore()
    },
    saveToStore () {
      localStorage.setItem('VUE-TODOS', JSON.stringify(this.todos))
    }
  }
}
</script>
